# -*- coding: utf-8 -*-
import requests

from flask import Flask
from flask_login import LoginManager
from flask.ext.mongoengine import MongoEngine
from werkzeug.contrib.fixers import ProxyFix
from flask_wtf.csrf import CsrfProtect

from app.config import config

mongoen = MongoEngine()

login_manager = LoginManager()

csrf = CsrfProtect()

def create_app(config_name):
    app = Flask(__name__, template_folder='templates', static_folder='static')

    app.app_context().push()

    app.wsgi_app = ProxyFix(app.wsgi_app)

    csrf.init_app(app)

    cfg = config[config_name]
    app.config.from_object(cfg)
    if config_name == 'default':
        app.config.from_pyfile('local.conf', silent=True)

    login_manager.init_app(app)
    mongoen.init_app(app)

    register_routes(app)
    config_errcode(app)
    return app


def register_routes(_app):
    import app.api_v1  # 这里import是为了执行一遍文件，执行了@current_app.route装饰器，即注册路由器
    import app.admin
    return _app


def config_errcode(app):
    try:
        resp = requests.get(app.config['ERRCODE_HOST'])
        app.config['errcode'] = resp.json()
    except Exception as e:
        raise Exception("Get error code failed, reason: %s" % e)

